package com.lcn.comm.framework.task;

import java.util.*;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017-12-25 11:55
 */
public class TaskGroup {

    /**
     * 唯一标识
     */
    private String groupId;

    /**
     * 事务状态 0：失败 1:成功
     */
    private int state;

    /**
     * 任务列表
     */
    private Map<String, TxTask> taskMap;

    public TaskGroup() {
        taskMap = new LinkedHashMap<String, TxTask>();
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public Map<String, TxTask> getTaskMap() {
        return taskMap;
    }

    public void setTaskMap(Map<String, TxTask> taskMap) {
        this.taskMap = taskMap;
    }

    public void addTask(TxTask txTask) {
        taskMap.put(txTask.getRequestId(), txTask);
    }

    /**
     * 当前事务组是否处于等待状态
     *
     * @return
     */
    public boolean isAwait() {
        Set<Map.Entry<String, TxTask>> entrySet = taskMap.entrySet();
        Iterator<Map.Entry<String, TxTask>> iter = entrySet.iterator();
        while (iter.hasNext()) {
            Map.Entry<String, TxTask> entry = iter.next();
            if (!entry.getValue().isAwait()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 明细task是否已删除
     *
     * @return
     */
    public boolean isRemove() {
        Set<Map.Entry<String, TxTask>> entrySet = taskMap.entrySet();
        Iterator<Map.Entry<String, TxTask>> iter = entrySet.iterator();
        while (iter.hasNext()) {
            Map.Entry<String, TxTask> entry = iter.next();
            if (!entry.getValue().isRemove()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 唤醒所有的任务
     */
    public void signalTask() {
        Set<Map.Entry<String, TxTask>> entrySet = taskMap.entrySet();
        Iterator<Map.Entry<String, TxTask>> iter = entrySet.iterator();
        while (iter.hasNext()) {
            Map.Entry<String, TxTask> entry = iter.next();
            entry.getValue().setState(state);
            entry.getValue().signalTask();
        }
    }
}
